package Test;

import io.PWDemo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Server {
    private ServerSocket serverSocket;
    public static void main(String[] args) {
        Server server = new Server();
        String []UserPwd = server.ReadUserFile();
        server.start(UserPwd[0],UserPwd[1]);
    }
    public   String []  ReadUserFile() {
        String[] UserPwd = new String[2];
        try {
            FileInputStream fis = new FileInputStream("./src/main/java/Test/User.txt");
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String User = br.readLine();
            String pwd = br.readLine();
            UserPwd[0] = User;
            UserPwd[1] = pwd;
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            return UserPwd;
        }
    }
    public Server() {
        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void  start(String name,String pwd) {
        String info = "";
        try {
            System.out.println("等待客户端连接");
            Socket socket = serverSocket.accept();
            System.out.println("一个客户端连接了");
            InputStream in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            if (name.equals(br.readLine()) && pwd.equals(br.readLine())) {
                info = "登录成功,用户名：" + name + "密码：" + pwd;
            } else {
                info = "账号密码错误";
            }
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);
            pw.println(info);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
